<?php

class EAPIxml{

	protected $apiCore;
	protected $apiCache;

	public function __Construct($apiCore){

		$this->apiCore = $apiCore;
		$this->apiCache = new EAPICache();
		date_default_timezone_set('Etc/GMT+0');
		//print date($this->apiCore['__APITime']);
	}

	public function __Destruct(){}

	public function getXML($path,EAPIUser $uObj=null,$usrAuth=false){
		try{
			if(empty($path)){

				throw new EAPIException('No XML Path Defined',604.1);

			}

			//print "<pre>";print_r($uObj);print "</pre>";

			if($usrAuth){
				$params = http_build_query(array("names" => $usrAuth['__User']));
			}
			if(isset($uObj)){
				$params = http_build_query($this->setAuthentication($uObj));
			}
			
			if($this->apiCache->checkCache($this->apiCore['__APISite'], $path, $params)){
				//print "<br/>Cache Was Found<br/>";
				//print "<pre>";print_r($this->apiCore['__APISite'].$path."/".$params);print "</pre>";
				return $this->apiCache->getCache($path, $params);
			}else{
				
				if(empty($params)){
					
					throw new EAPIException('No XML Query Defined',604.6);
				}
	
				$ch = curl_init();
				$url = $this->apiCore['__APISite']."/".$path;
	
				$headers[] = "POST " . $path . " HTTP/1.0\r\n";
				$headers[] = "Host: " . $this->apiCore['__APISite'] . "\r\n";
				$headers[] = "Content-Type: application/x-www-form-urlencoded\r\n";
				$headers[] = "User-Agent: PHPApi\r\n";
				$headers[] = "Content-Length: " . strlen($params) . "\r\n";
				$headers[] = "Connection: close\r\n\r\n";
	
				//print $poststring;
	
				// set URL and other appropriate options
				$options = array(CURLOPT_URL => $url,
				//CURLOPT_HTTPHEADER => $headers,
				CURLOPT_RETURNTRANSFER => 1,
				CURLOPT_CONNECTTIMEOUT => 5,
				CURLOPT_POST => 1,
				CURLOPT_POSTFIELDS => $params
				);
				//print "<pre>";print_r($options);print "</pre>";
	
				curl_setopt_array($ch, $options);
	
				$output = curl_exec($ch);
	
				//print "<pre>";print_r($output);print "</pre>";
	
				//if any data was returned from CURL
				if($output){

					//check the data for any API XML errors
					if($this->checkErrors($output)){

						$xml = new SimpleXMLElement($output);
						$cachedUntil = $xml->{'cachedUntil'};
						
						$this->apiCache->setCache($this->apiCore['__APISite'], $path, $params, $output, $cachedUntil);
						//print "<br/>Cache Updated<br/>";
						//if no XML errors found
						//return the XML output
						return $output;
					}
					//print "<br/>Cache Not Updated<br/>";
					//if XML errors exist
					return $output;
					
				}else{
					
					//if no CURL output exists, throw exception
					throw new EAPIException('Could Not Retrieve API Data',604.2);
					
				}
			}

		}catch(EAPIException $e){
			return $e;
		}
	}

	private function setAuthentication(EAPIUser $uObj){

		//http://wiki.eve-id.net/APIv2_Eve_CharacterID_XML
		//needs to use the retrieved character ID from the character XML
		return array("userID" => $uObj->getAPIUser(),"apiKey" => $uObj->getAPIKey(),"characterID" => $uObj->getUserID());

	}

	public function setCredentials($userName,$apiUser,$apiKey){
		try{
			$charData = $this->getXML('/eve/CharacterID.xml.aspx',null,array("__User" => $userName, "__APIUser" => $apiUser, "__APIKey" => $apiKey));

			if($this->apiCore['__APIDebug']=="xml"){
				print "<pre>".__CLASS__.":".__LINE__."<br/>";print_r($charData);print "</pre>";
			}

			if(isset($charData)){
				 
				//create the XML reader class
				$xml = new XMLReader();

				//load the external XML if possible
				if($xml->XML($charData)){
						
					//loop through each XML Node
					while($xml->read()){
							
						//grab the characterID attribute if matched
						//on the current node
						$characterID = (string)$xml->getAttribute('characterID');
							
						//if the characterID has been found
							
						if($characterID){

							//close the XML reader class
							//we have the data we are after
							$xml->close();

							// return the characterID
							return $characterID;

						}

					}

				}
				
				//close the XML reader class
				$xml->close();
							
				//if a characterID was never found in the
				//XML nodes, throw an exception
				throw new EAPIException('Could Not Find Character ID',604.3);

				//if there was no XML returned
			}else{

				//throw an exception saying that no
				//credentials could be set
				throw new EAPIException('Could Not Set User Credentials',604.4);

			}

			//catch any exceptions thrown IF any
		}catch (EAPIException $e){

			//print the exception to the user
			print $e;

			//return a false statement to abort any functions
			return false;
		}
	}
	
	private function checkErrors($xmlData){
		try{
			if(isset($xmlData)){
					 
				//create the XML reader class
				$xml = new XMLReader();
	
				//load the external XML if possible
				if($xml->XML($xmlData)){
							
					//loop through each XML Node
					while($xml->read()){
								
						//grab the errorID attribute if matched
						//on the current node
						$errorID = (string)$xml->getAttribute('code');
						$errorString = (string) $xml->readString();
								
						//if the characterID has been found
						if($errorID){
	
							//close the XML reader class
							//we have the data we are after
							$xml->close();
	
							//return the Eve Online API error
							throw new EAPIException($errorString,$errorID);
							return false;
	
						}
	
					}
	
				}
				//close the XML reader class
				$xml->close();
				
				//return the XML data
				return $xmlData;
				
			}
			
			throw new EAPIException('No XML Data In Error Check',604.5);
			
		}catch(EAPIException $e){
			
			print $e;
			die();
			
		}
		
	}
	
};
?> 